package service.Impl;

import service.PickNameServcie;
import utils.Constants;
import utils.FileUtil;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class PickNameServiceImpl implements PickNameServcie {
    @Override
    public void clearFile() throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter(Constants.CALLEDPATH));
        bw.write("");
        bw.close();
    }

    @Override
    public String pickName(String type) throws IOException, ExecutionException, InterruptedException {
        if (type.equals(Constants.UNFAIR)){
            //不公平点名
            List<String> list = FileUtil.loadFile(Constants.PATH);
            //产生随机数
            int i = (int) (Math.random()* list.size());
            String s = list.get(i);
            return s;
        }else {
            //公平点名（思路：将已点过的名存进txt文件，下次不点他）
            ExecutorService es = Executors.newFixedThreadPool(8);
            Future<List<String>> submit = es.submit(new Callable<List<String>>() {
                @Override
                public List<String> call() throws Exception {
                    return FileUtil.loadFile(Constants.PATH);
                }
            });
            Future<List<String>> submit2 = es.submit(new Callable<List<String>>() {
                @Override
                public List<String> call() throws Exception {
                    return FileUtil.loadFile(Constants.CALLEDPATH);
                }
            });

            //原始学生姓名列表
//            List<String> originList = FileUtil.loadFile(Constants.PATH);
            List<String> originList = submit.get();
            //获取已经点过的名
//            List<String> calledList = FileUtil.loadFile(Constants.CALLEDPATH);
            List<String> calledList = submit2.get();
            boolean b = originList.removeAll(calledList);
            if (originList.size() == 0){
                return "学生全被点过了～";
            }
            //产生随机数
            int i = (int)(Math.random()* originList.size());
            String name = originList.get(i);
            writeToFile(name);
            return name;
        }
    }
    public void writeToFile(String str) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter(Constants.CALLEDPATH,true));
        bw.write(str + "\n");
        //关闭写入流
        bw.close();
    }
}
